import { memo } from 'react'
import { styled } from '@umijs/max'
import { InputNumber, Modal, TimePicker } from 'antd'
import { dayjs2minutes, minutes2dayjs } from '@/utils/common'
import dayjs from 'dayjs'
import { Access } from '@umijs/max'
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons'
import getUUID from '@/utils/getUUID'

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;

  .row {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 8px;
  }
`

export type OccupyFee = {
  startTime: number
  endTime: number
  price: number
  fakeId: number | string
}
export interface OccupyFeeProps {
  value?: OccupyFee[]
  onChange?: (value: OccupyFee[]) => void
}

/** 最晚结束时间 23:59 -> 1439 */
const LastEndTime = 1439
const Hours: number[] = new Array(24).fill(0).map((_,i) => i)
const Minutes: number[] = new Array(60).fill(0).map((_,i) => i)
const getDisabledTime = (min: number, max: number) => {
  const minHour = Math.floor(min / 60)
  const minMinute = min % 60
  const maxHour = Math.floor(max / 60)
  const maxMinute = max % 60
  return {
    disabledHours: () => Hours.filter(it => it < minHour || it > maxHour),
    disabledMinutes: (h: number) => {
      if (h === minHour) {
        return Minutes.filter(it => it < minMinute)
      } else if (h === maxHour) {
        return Minutes.filter(it => it > maxMinute)
      } else if (h > maxHour || h < minHour) {
        return Minutes
      }
      return []
    }
  }
}

const OccupyFeeComponent: React.FC<OccupyFeeProps> = props => {
  const list = props.value || []

  const setList = (value: OccupyFee[]) => {
    props.onChange?.(value)
  }

  const onEndTimeChange = (val: dayjs.Dayjs, item: OccupyFee) => {
    let targetIndex = 0, endTime = 0
    setList(list.map((_item, _index) => {
      if (_item.fakeId !== item.fakeId) {
        if (_index === targetIndex + 1) {
          return {
            ..._item,
            startTime: endTime + 1,
          }
        }
        return _item
      }
      targetIndex = _index
      endTime = dayjs2minutes(val)
      return {
        ..._item,
        endTime,
      }
    }))
  }

  const onPriceChange = (price: number | null, item: OccupyFee) => {
    setList(list.map(_item => {
      if (_item.fakeId !== item.fakeId) return _item
      return {
        ..._item,
        price: price || 0,
      }
    }))
  }

  const add = () => {
    const last = list.at(-1)!
    if (last.endTime === LastEndTime) {
      Modal.warning({
        title: '提示',
        content: '已无剩余时间可添加'
      })
      return
    }
    setList(list.concat([{
      fakeId: getUUID(),
      startTime: last.endTime + 1,
      endTime: LastEndTime,
      price: 0,
    }]))
  }

  const remove = (index: number) => {
    setList(list.filter((_, _index) => _index !== index ))
  }

  return (
    <Container>
      <span>计费区间</span>
      {
        list.map((item, index) => {
          const isLast = index === list.length - 1
          return <div className='row' key={item.fakeId}>
            <TimePicker
              format='HH:mm' allowClear={false} disabled
              value={minutes2dayjs(item.startTime)}
            />
            <TimePicker
              format='HH:mm' allowClear={false}
              value={minutes2dayjs(item.endTime)}
              onChange={val => onEndTimeChange(val!, item)}
              disabledTime={() => getDisabledTime(item.startTime + 1, isLast ? LastEndTime : list[index + 1].endTime - 2)}
            />
            <InputNumber
              placeholder='价格' 
              addonAfter='元' 
              min={0}
              precision={2}
              value={item.price}
              onChange={value => onPriceChange(value, item)}
              style={{width: 140}}
            />
            <span>/每分钟</span>
            <Access accessible={isLast && list.length < 6}>
              <PlusCircleOutlined style={{color: 'green', cursor: 'pointer'}} onClick={add} />
            </Access>
            <Access accessible={isLast && index > 0}>
              <MinusCircleOutlined style={{color: 'red', cursor: 'pointer'}} onClick={() => remove(index)} />
            </Access>
          </div>
        })
      }
      {/* <span>最多可设置6个时段，计费单价不能超过<span style={{color: 'var(--ant-color-primary)'}}>0.5元/分钟</span></span> */}
      <span>最多可设置6个时段</span>
    </Container>
  )
}

export default memo(OccupyFeeComponent)
